//面板的功能，主要实现面板元素的排序，位置互换
import { fabric } from 'fabric'
import EventEmitter from './EventEmitter.class.js'
export default class Panel extends EventEmitter {
  constructor(options) {
    super()
    this.options = options
    this.group = options.group
    this.component = this.group.component
    this.list = this.group.list
    this.elemlist = this.group.elemlist
  }
  move(item, distance = 0, swapIndex = -1) {
    let index = this.list.indexOf(item)
    if (index > -1) {
      if (swapIndex == -1) swapIndex = index + distance
      let swapItem = this.list[swapIndex]
      let swapObject = this.component._objects[swapIndex]
      if (swapItem) {
        this.list[swapIndex] = item
        this.list[index] = swapItem
        //这里两个都要改变，不好，需要优化，但是顺序决定了渲染顺序了
        this.component._objects[swapIndex] = this.component._objects[index]
        this.component._objects[index] = swapObject
        this.emit('move')
      }
    }
  }
  remove(item) {
    fabric.util.removeFromArray(this.component._objects, item.component)
    fabric.util.removeFromArray(this.list, item)
  }
  moveTop(item) {
    this.remove(item)
    this.insertAt(item, 0)
    this.emit('move')
  }
  moveBottom(item) {
    this.remove(item)
    this.insertAt(item, this.list.length)
    this.emit('move')
  }
  insertAt(item, index) {
    this.list.splice(index, 0, item)
    this.component.insertAt(item.component, index)
  }
  add(item) {
    this.list.push(item)
    if (this.component.type == 'group') {
      this.component.addWithUpdate(item.component)
    } else {
      this.component.add(item.component)
    }
  }
  index(item) {
    return this.list.indexOf(item)
  }
}
